<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2019 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://demo.thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\admin\controller\permission;

use app\admin\service\NodeService;
use library\Controller;
use library\tools\Data;
use think\Db;

/**
 * 用户管理
 * Class User
 * @package app\admin\controller\permission
 */
class User extends Controller
{

    /**
     * 指定当前数据表
     * @var string
     */
    public $table = 'SystemUser';

    /**
     * 用户管理
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {
        $this->title = '用户管理';
        $department = Db::name('system_department')->order('sort desc,id desc')->column('dep_title','id');
        $this->type_op = assemble_op([''=>'-- 全部部门 --'], $department);
        $query = $this->_query($this->table)->like('username,nickname')->equal('status,department_id');
        $query->dateBetween('login_at,create_at')->where(['is_deleted' => '0'])->order('id desc')->page();
    }
    
    
    /**
     * 列表数据处理
     * @auth true
     * @param array $data
     * @throws \Exception
     */
    protected function _index_page_filter(&$data)
    {  	
        foreach ($data as &$vo) {
        	$vo['department_cn'] = Db::name('system_department')->where(['id'=>$vo['department_id']])->value('dep_title');
        	$vo['authorize_cn'] = Db::name('system_auth')->where(['id'=>$vo['authorize']])->value('title');
        }
    }

    /**
     * 添加用户
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function add()
    {
        $this->applyCsrfToken();
        $this->_form($this->table, 'form');
    }
    
    
    
    /**
     * 表单数据后置处理
     * @param array $data
     * @auth true
     */
    protected function _add_form_result($id)
    {
		$user = Db::name($this->table)->where(['id'=>$id])->find();
		if($user){
			if (Data::save($this->table, ['id' => $id, 'password' => md5('123456'),'username'=>number_rule_max(1)], 'id')) {
                save_number_rule_max(1);
            }
            sysoplog('用户管理', '添加'.$user['nickname'].'用户成功');
		}
    }


    /**
     * 编辑用户
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function edit()
    {   	
        $this->applyCsrfToken();
        $this->_form($this->table, 'form');
    }
    
    
    /**
     * 表单数据后置处理
     * @param array $data
     * @auth true
     */
    protected function _edit_form_result($id)
    {
		$user = Db::name($this->table)->where(['id'=>$id])->find();
		if($user){
            sysoplog('用户管理', '编辑'.$user['nickname'].'用户成功');
		}
    }

    /**
     * 修改用户密码
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function pass()
    {
        $this->applyCsrfToken();
        if ($this->request->isGet()) {
            $this->verify = false;
            $this->_form($this->table, 'pass');
        } else {
            $post = $this->request->post();
            if ($post['password'] !== $post['repassword']) {
                $this->error('两次输入的密码不一致！');
            }
            $result = NodeService::checkpwd($post['password']);
            if (empty($result['code'])) $this->error($result['msg']);
            if (Data::save($this->table, ['id' => $post['id'], 'password' => md5($post['password'])], 'id')) {
            	sysoplog('用户管理', '修改'.Db::name($this->table)->where(['id'=>$post['id']])->value('nickname').'用户密码成功');
                $this->success('密码修改成功，下次请使用新密码登录！', '');
            } else {
                $this->error('密码修改失败，请稍候再试！');
            }
        }
    }

    /**
     * 表单数据处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function _form_filter(&$data)
    {
        if ($this->request->isPost()) {
            NodeService::applyUserAuth();
            $data['authorize'] = (isset($data['authorize']) && is_array($data['authorize'])) ? join(',', $data['authorize']) : '';
//          if (isset($data['id'])) {
//              unset($data['nickname']);
//          } 
        } else {
            $data['authorize'] = explode(',', isset($data['authorize']) ? $data['authorize'] : '');
            $this->authorizes = Db::name('SystemAuth')->where(['status' => '1'])->order('sort desc,id desc')->select();
            $department = Db::name('system_department')->order('sort desc,id desc')->field('id,dep_title')->select();
    		$this->dep_op = array_column($department,'dep_title','id');
        }
    }

    /**
     * 禁用用户
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function forbid()
    {
        if (in_array('10000', explode(',', $this->request->post('id')))) {
            $this->error('系统超级账号禁止操作！');
        }
        $this->applyCsrfToken();
        $this->_save($this->table, ['status' => '0']);
    }

    /**
     * 启用用户
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function resume()
    {
        $this->applyCsrfToken();
        $this->_save($this->table, ['status' => '1']);
    }

    /**
     * 删除用户
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function remove()
    {
        if (in_array('10000', explode(',', $this->request->post('id')))) {
            $this->error('系统超级账号禁止删除！');
        }
        $this->applyCsrfToken();
        $this->_delete($this->table);
    }
    
    
    /**
	 * 删除结果处理
	 * @param boolean $result
	 * @throws \think\Exception
	 * @throws \think\exception\PDOException
	 */
	protected function _remove_delete_result($result)
	{
	    if ($result) {
	        $id = $this->request->post('id');
	        $info = Db::name($this->table)->where(['id'=>$id])->find();
	        sysoplog('用户管理', '删除'.$info['nickname'].'用户成功');
	    } else {
	        $this->error("用户删除失败，请稍候再试！");
	    }
	}

}
